package com.czr.dao.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czr.dao.entity.*;
import com.czr.dao.mapper.*;
import com.czr.dao.service.CzrPostService;
import com.czr.dao.service.CzrReplyService;
import com.czr.dto.CzrPostParam;
import com.czr.dto.DelPostParam;
import com.czr.util.DateUtils;
import com.czr.util.PageUtil;
import com.czr.util.TencentCosUtil;
import com.czr.vo.CzrPostVo;
import com.czr.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 栏目表 服务实现类
 * </p>
 */
@Service
public class CzrPostServiceImpl extends ServiceImpl<CzrPostMapper, CzrPost> implements CzrPostService {

    @Autowired
    public CzrPostMapper czrPostMapper;

    @Autowired
    public CzrUserMapper czrUserMapper;


    @Autowired
    public CzrLikeMapper czrLikeMapper;

    @Autowired
    public CzrReplyService czrReplyService;

    @Autowired
    public CzrReplyMapper czrReplyMapper;

    @Override
    public Result<Object> czrPost(CzrPost czrPost) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        czrPost.setPubTime(format.format(new Date()));
        czrPost.setLikeCount(0);
        czrPost.setReadingCount(0);
        czrPost.setImage(czrPost.getImageName().toString());
        czrPost.setImageName(null);
        czrPost.setStatus(0);
        boolean resultBoolen = czrPost.insert();
        if (resultBoolen) {
            return Result.success(200, "发帖成功！");
        } else {
            return Result.fail("发帖失败！");
        }
    }

    @Override
    public Result<Object> list(CzrPostParam czrPostParam, Integer userId) throws Exception {
        TencentCosUtil tencentCosUtil=new TencentCosUtil();
        Page<CzrPost> page = new Page<>();
        page.setSize(czrPostParam.getSize());
        page.setCurrent(czrPostParam.getCurrent());
        LambdaQueryWrapper<CzrPost> ew = new LambdaQueryWrapper<>();
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(czrPostParam.getKeyword())) {
            ew.like(CzrPost::getTitle, czrPostParam.getKeyword());
        }
        ew.eq(CzrPost::getColumnId, czrPostParam.getColumnId());
        ew.eq(CzrPost::getStatus, 1);
        ew.orderByDesc(CzrPost::getPubTime);
        page = this.getBaseMapper().selectPage(page, ew);
        JSONArray jsonArray = new JSONArray();
        for (CzrPost czrPost : page.getRecords()) {
            CzrPostVo czrPostVO = new CzrPostVo();
            BeanUtils.copyProperties(czrPost, czrPostVO);
            //查询用户表
            Map<String, Object> map = czrUserMapper.getUserInfo(czrPost.getUserId());
            if (!StringUtils.isEmpty(map)) {
                czrPostVO.setNickName(map.get("nick_name").toString());
                czrPostVO.setUserLogo(tencentCosUtil.imgFile_wx(map.get("user_logo").toString()));
            }
            if (userId == null) {
                czrPostVO.setIsLike(0);
                czrPostVO.setIsDel(0);
            } else {
                List<CzrLike> czrLikeList = czrLikeMapper.getLikePostId(Integer.parseInt(czrPostVO.getId().toString()), userId);
                if (czrLikeList.size() > 0) {
                    czrPostVO.setIsLike(1);
                } else {
                    czrPostVO.setIsLike(0);
                }
            }
            if (!StringUtils.isEmpty(userId) && czrPost.getUserId().equals(Long.parseLong(userId + ""))) {
                czrPostVO.setIsDel(1);
            } else {
                czrPostVO.setIsDel(0);
            }
//            if (userId != null) {
//                CzrUser czrUser = czrUserMapper.selectById(userId);
//                if (czrUser.getUserType() == 1) {
//                    czrPostVO.setIsDel(1);
//                }
//            }

            if (!StringUtils.isEmpty(czrPost.getImage())) {
                JSONArray array=JSONArray.parseArray(czrPost.getImage());
                JSONArray array1=new JSONArray();
                for (Object obj:array){
                    String path=tencentCosUtil.imgFile_wx(obj.toString());
                    array1.add(path);
                }
                czrPostVO.setImage(array1);
//                czrPostVO.setImage(JSONArray.parseArray(czrPost.getImage()));
            }
            if(!StringUtils.isEmpty(czrPost.getThumbnail())){
                czrPostVO.setThumbnail(tencentCosUtil.imgFile_wx(czrPost.getThumbnail()));
            }
            czrPostVO.setPubTime(DateUtils.getTimeDescriptionByDate(new Date(), czrPostVO.getPubTime()));
            Integer count = czrReplyMapper.getPostCount(czrPost.getId());
            czrPostVO.setPostCount(count);
            jsonArray.add(czrPostVO);
        }
        JSONObject object = PageUtil.getPage(jsonArray, page);
        return Result.data(object);
    }
    @Override
    public Result<Object> glList(CzrPostParam czrPostParam, Integer userId) throws Exception {
        TencentCosUtil tencentCosUtil=new TencentCosUtil();
        Page<CzrPost> page = new Page<>();
        page.setSize(czrPostParam.getSize());
        page.setCurrent(czrPostParam.getCurrent());
        LambdaQueryWrapper<CzrPost> ew = new LambdaQueryWrapper<>();
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(czrPostParam.getKeyword())) {
            ew.like(CzrPost::getTitle, czrPostParam.getKeyword());
        }
        ew.eq(CzrPost::getColumnId, czrPostParam.getColumnId());
        ew.notIn(CzrPost::getStatus, -1);
        ew.orderByDesc(CzrPost::getPubTime);
        page = this.getBaseMapper().selectPage(page, ew);
        JSONArray jsonArray = new JSONArray();
        for (CzrPost czrPost : page.getRecords()) {
            CzrPostVo czrPostVO = new CzrPostVo();
            BeanUtils.copyProperties(czrPost, czrPostVO);
            //查询用户表
            Map<String, Object> map = czrUserMapper.getUserInfo(czrPost.getUserId());
            if (!StringUtils.isEmpty(map)) {
                czrPostVO.setNickName(map.get("nick_name").toString());
                czrPostVO.setUserLogo(tencentCosUtil.imgFile_wx(map.get("user_logo").toString()));
            }
            if (userId == null) {
                czrPostVO.setIsLike(0);
                czrPostVO.setIsDel(0);
            } else {
                List<CzrLike> czrLikeList = czrLikeMapper.getLikePostId(Integer.parseInt(czrPostVO.getId().toString()), userId);
                if (czrLikeList.size() > 0) {
                    czrPostVO.setIsLike(1);
                } else {
                    czrPostVO.setIsLike(0);
                }
            }
            if (!StringUtils.isEmpty(userId) && czrPost.getUserId().equals(Long.parseLong(userId + ""))) {
                czrPostVO.setIsDel(1);
            } else {
                czrPostVO.setIsDel(0);
            }
//            if (userId != null) {
//                CzrUser czrUser = czrUserMapper.selectById(userId);
//                if (czrUser.getUserType() == 1) {
//                    czrPostVO.setIsDel(1);
//                }
//            }

            if (!StringUtils.isEmpty(czrPost.getImage())) {
                JSONArray array=JSONArray.parseArray(czrPost.getImage());
                JSONArray array1=new JSONArray();
                for (Object obj:array){
                    String path=tencentCosUtil.imgFile_wx(obj.toString());
                    array1.add(path);
                }
                czrPostVO.setImage(array1);
//                czrPostVO.setImage(JSONArray.parseArray(czrPost.getImage()));
            }
            if(!StringUtils.isEmpty(czrPost.getThumbnail())){
                czrPostVO.setThumbnail(tencentCosUtil.imgFile_wx(czrPost.getThumbnail()));
            }
            czrPostVO.setPubTime(DateUtils.getTimeDescriptionByDate(new Date(), czrPostVO.getPubTime()));
            Integer count = czrReplyMapper.getPostCount(czrPost.getId());
            czrPostVO.setPostCount(count);
            jsonArray.add(czrPostVO);
        }
        JSONObject object = PageUtil.getPage(jsonArray, page);
        return Result.data(object);
    }

    @Override
    public Result<Object> addReading(Integer postId) throws Exception {
        CzrPost czrPost = this.getById(postId);
        CzrPost czrPost1 = new CzrPost();
        czrPost1.setId(Long.valueOf(postId));
        int readingcount = czrPost.getReadingCount();
        readingcount++;
        czrPost1.setReadingCount(readingcount);
        boolean resultBoolen = czrPost1.updateById();
        if (resultBoolen) {
            return Result.success(200, "成功！");
        } else {
            return Result.success(201, "无效帖子ID！");
        }
    }

    @Override
    public Result<Object> auditing(Integer postId,Integer status) throws Exception {
        CzrPost czrPost = this.getById(postId);
        czrPost.setStatus(status);
        boolean resultBoolen = czrPost.updateById();
        if (resultBoolen) {
            return Result.success(200, "成功！");
        } else {
            return Result.success(201, "无效帖子ID！");
        }
    }

    @Override
    public Result<Object> addLike(Integer postId, Integer type, Integer userId) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (type == 0) {
            CzrPost czrPost = this.getById(postId);
            //判断该用户是否已对该帖子点赞
            List<CzrLike> czrLikeList = czrLikeMapper.getLikePostId(postId, userId);
            if (czrLikeList.size() == 0) {
                CzrPost czrPost1 = new CzrPost();
                czrPost1.setId(Long.valueOf(postId));
                int likeCount = czrPost.getLikeCount();
                likeCount++;
                czrPost1.setLikeCount(likeCount);
                boolean resultBoolen = czrPost1.updateById();
                if (resultBoolen) {
                    CzrLike czrLike = new CzrLike();
                    czrLike.setPostId(postId);
                    czrLike.setType(type);
                    czrLike.setPubTime(format.format(new Date()));
                    czrLike.setUserId(userId);
                    czrLike.insert();
                    return Result.success(200, "成功！");
                } else {
                    return Result.success(201, "失败！");
                }
            } else {
                return Result.success(201, "该帖子已点赞！");
            }

        } else if (type == 1) {
            CzrReply czrReply = czrReplyService.getById(postId);
            //判断该用户是否已对该帖子点赞
            List<CzrLike> czrLikeList = czrLikeMapper.getLikeReplyId(postId, userId);
            if (czrLikeList.size() == 0) {
                CzrReply czrReply1 = new CzrReply();
                czrReply1.setId(Long.valueOf(postId));
                int likeCount = czrReply.getLikeCount();
                likeCount++;
                czrReply1.setLikeCount(likeCount);
                boolean resultBoolen = czrReply1.updateById();
                if (resultBoolen) {
                    CzrLike czrLike = new CzrLike();
                    czrLike.setReplyId(postId);
                    czrLike.setType(type);
                    czrLike.setPubTime(format.format(new Date()));
                    czrLike.setUserId(userId);
                    czrLike.insert();
                    return Result.success(200, "成功！");
                } else {
                    return Result.success(201, "失败！");
                }
            } else {
                return Result.success(201, "该帖子已点赞！");
            }
        }

        return null;
    }

    @Override
    public Result<Object> delPost(DelPostParam delPostParam, JSONObject cacheToken) throws Exception {
        CzrPost czrPost = czrPostMapper.selectById(delPostParam.getPostId());
        if (!czrPost.getUserId().equals(cacheToken.getLong("id")) && cacheToken.getLong("u_identity") != 3) {
            return Result.success(201, "该帖子非本用户发帖，无法删除！");
        }
        Boolean b = czrPost.deleteById(delPostParam.getPostId());
        if (b) {
            return Result.success(200, "删除成功！");
        } else {
            return Result.success(201, "删除失败！");
        }
    }

    @Override
    public Result<Object> getInfo(Integer id) throws Exception {
        CzrPost czrPost=czrPostMapper.selectById(id);
        if (czrPost!=null){
            if(czrPost.getStatus()==1){
                return Result.data(200, czrPost, "");
            }
        }

        return Result.data(200, "", "");
    }

}
